package xin.ryven.car.android.utils

import android.content.Context
import android.util.Log
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import xin.ryven.car.android.data.Music
import java.io.File
import java.io.FileOutputStream
import java.net.HttpURLConnection
import java.net.URL

class FileDownloader {
    companion object {
        private const val TAG = "FileDownloader"

        suspend fun downloadFile(
            context: Context,
            music: Music,
            playlistName: String = "默认歌单"
        ): Boolean = withContext(Dispatchers.IO) {
            try {
                // 构建保存路径
                val musicFile = FileUtils.getMusicFile(context, music)
                val lrcFile = FileUtils.getLrcFile(context, music)

                // 确保目录存在
                musicFile.parentFile?.mkdirs()

                // 下载音乐文件
                downloadSingleFile(music.downloadUrl, musicFile)
                
                // 验证下载的文件
                if (!isValidFlacFile(musicFile)) {
                    Log.e(TAG, "Downloaded file is not a valid FLAC file")
                    musicFile.delete()
                    return@withContext false
                }

                // 下载歌词文件
                if (!music.lrcUrl.isNullOrEmpty()) {
                    downloadSingleFile(music.lrcUrl, lrcFile)
                }

                Log.d(TAG, "Successfully downloaded: ${music.name}")
                true
            } catch (e: Exception) {
                Log.e(TAG, "Error downloading file: ${music.name}", e)
                false
            }
        }

        private suspend fun downloadSingleFile(url: String, outputFile: File) {
            val connection = URL(url).openConnection() as HttpURLConnection
            connection.connectTimeout = 15000
            connection.readTimeout = 15000

            connection.inputStream.use { input ->
                FileOutputStream(outputFile).use { output ->
                    input.copyTo(output)
                }
            }
        }

        private fun isValidFlacFile(file: File): Boolean {
            return try {
                file.inputStream().use { input ->
                    val header = ByteArray(4)
                    input.read(header)
                    String(header) == "fLaC"
                }
            } catch (e: Exception) {
                Log.e(TAG, "Error checking FLAC file", e)
                false
            }
        }
    }
} 